﻿using System;
using Eflong.Utility;

namespace Eflong.KJFiles
{
    public class TDAuto_DevFiles : DevFile
    {
        private string[ ] oldBbodys = null;

        public override bool ParseContent( string content )
        {
            if ( dic_Fields.Count == 0 )
            {
                InitTDAutoFields( );
            }

            bool result = true;

            string[ ] separators = { "\r\n" };
            string[ ] bodys = content.Split( separators , new StringSplitOptions( ) );

            // 解析文件头

            ParseParas( bodys[ 0 ] );
            if ( devNum == 0 || bodys.Length < 2 )
            {
                return false;
            }
            devNum = Math.Min( devNum , bodys.Length - 1 );

            // 解析文件体

            for ( int i = 1; i <= devNum; i++ )
            {
                string body = bodys[ i ].Trim( );
                if ( body.IndexOf( '\0' ) < 0 && body != "" )
                {
                    try
                    {
                        ParseBody( body );
                    }
                    catch ( Exception ex )
                    {
                        LogWrapper.Logger.Error( " KJ QHWL_DevFile : " + body + " err: " + ex.Message );
                    }
                }
                else
                {
                    devNum = i - 1;
                    break;
                }
            }

            return result;
        }

        /// <summary>
        /// 解析头
        /// </summary>
        /// <param name="head"></param>
        /// <returns></returns>
        public override bool ParseParas( string head )
        {
            bool result = false;
            string[ ] hs = head.Split( ',' );
            if ( hs.Length > 3 )
            {
                timeDev = DateTime.Parse( hs[ 1 ] );
                devNum = Convert.ToInt16( hs[ 2 ] );
            }
            return result;
        }

        /// <summary>
        /// 解析测点信息
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public override DevItem ParseBody( string body )
        {
            string[ ] bs = body.Split( ',' );
            DevItem item = new DevItem( );

            // 保证开关量/控制量的单位是空
            if ( dic_Fields.ContainsKey( "分站号" ) )
            {
                item.FZNO = bs[ dic_Fields[ "分站号" ] ];
            }
            else
            {
                item.FZNO = string.Empty;
            }
            item.SensorNO = bs[ dic_Fields[ "分站号" ] ] + "-" + bs[ dic_Fields[ "测点号" ] ];

            item.Location = bs[ dic_Fields[ "安装位置" ] ].Trim( );

            item.SersorUnit = bs[ dic_Fields[ "单位" ] ].Trim( );

            item.SersorType = bs[ dic_Fields[ "传感器类型" ] ];

            item.SersorName = bs[ dic_Fields[ "传感器名称" ] ].Replace( " " , "" );

            // 保证开关量/控制量的单位是空

            int n = 1;
            if ( int.TryParse( item.SersorName , out n ) )
            {
                var typename = ( TDAuto_Types )n;
                item.SersorName = typename.ToString( );
            }
            else
            {
                throw new Exception( "传感器名称编号有问题：" + item.SersorName );
            }

            var type = ( TDAuto_SensorTypes )Convert.ToInt16( item.SersorType );

            // 必须考虑一些开关量，被识别为 模拟量了，
            if ( type == TDAuto_SensorTypes.模拟量 && ( item.SersorUnit == "" && item.SersorName != "人数" ) )
            {
            }

            if ( type == TDAuto_SensorTypes.其它 )
            {
                type = TDAuto_SensorTypes.开关量;
            }
            item.SersorType = type.ToString( );

            if ( type == TDAuto_SensorTypes.开关量 || type == TDAuto_SensorTypes.控制量 || type == TDAuto_SensorTypes.其它 )
            {
                item.SersorUnit = string.Empty;
                if ( item.SersorName == "开停" || item.SersorName == "开关" || item.SersorName.Contains( "其它" ) || item.SersorName.Contains( "故障" ) )
                {
                    item.SersorName = KJXXDigitalNameMatchForLocation( item.Location , item.SersorName );
                }
                else if ( item.SersorName == "主扇" && !item.Location.Contains( "主扇" ) && !item.Location.Contains( "风机" ) )
                {
                    // 避免错误的识别
                    // 水泵1#开停 类型是 20， 被当做主扇了
                    item.SersorName = KJXXDigitalNameMatchForLocation( item.Location );
                }
            }
            else
            {
                item.SersorType = "模拟量";
                if ( item.SersorName == "模拟量" || item.SersorName.Contains( "其它" ) || item.SersorName == "压力" )
                {
                    item.SersorName = KJXXAnalogNameMatchForLocation( item.Location );
                } // 设置模拟量的参数
                Set_AnalogParas( bs , ref item );
            }
            Add( item );
            return item;
        }

        /// <summary>
        ///
        /// 1,891,总回风尾端甲烷,4,1,%,,4.00,0.00,0.69,0.00,0,0
        /// 1,1154,四采区集中回风一氧化碳,1,1,PPm,,500.00,0.00,23.75,0.00,0,0
        /// 4,367,35KV1号电厂4403开关,28,2,分闸,合闸,0,0,0,0,0,0
        /// </summary>
        private void InitTDAutoFields( )
        {
            dic_Fields.Add( "分站号" , ( int )TDAuto_Fields.分站号 );

            dic_Fields.Add( "测点号" , ( int )TDAuto_Fields.测点号 );
            dic_Fields.Add( "安装位置" , ( int )TDAuto_Fields.安装位置 );
            dic_Fields.Add( "传感器名称" , ( int )TDAuto_Fields.传感器名称 );
            dic_Fields.Add( "传感器类型" , ( int )TDAuto_Fields.传感器类型 );

            dic_Fields.Add( "单位" , ( int )TDAuto_Fields.单位 );
            dic_Fields.Add( "量程下限" , ( int )TDAuto_Fields.量程下限 );
            dic_Fields.Add( "量程上限" , ( int )TDAuto_Fields.量程上限 );
            dic_Fields.Add( "报警下限" , ( int )TDAuto_Fields.报警下限 );
            dic_Fields.Add( "报警高限" , ( int )TDAuto_Fields.报警高限 );
            dic_Fields.Add( "解警值" , ( int )TDAuto_Fields.报警高限 );
            dic_Fields.Add( "断电值" , ( int )TDAuto_Fields.断电值 );
            dic_Fields.Add( "复电值" , ( int )TDAuto_Fields.复电值 );
        }
    }

    public class TDAuto_RtData : RtData
    {
        public override bool ParseContent( string content )
        {
            char[ ] separator = { '\r' , '\n' };
            string[ ] separators = { "\r\n" };
            string[ ] bodys = content.Split( separators , new StringSplitOptions( ) ); // 1024

            // 解析文件头

            ParseHead( bodys[ 0 ] );

            if ( devNum == 0 || bodys.Length < 2 )
            {
                return false;
            }
            devNum = Math.Min( devNum , bodys.Length - 1 );

            if ( bodys.Length >= 3 )
            {
                // 解决煤管局回写数据引起非正常报警的问题
                if ( !IsValid( bodys[ 1 ] ) && !IsValid( bodys[ 2 ] ) )
                    return false;
            }

            // 解析文件体

            for ( int i = 1; i <= devNum; i++ )
            {
                string body = bodys[ i ].Trim( );

                if ( !string.IsNullOrEmpty( body ) )
                {
                    try
                    {
                        ParseBody( body );
                    }
                    catch ( Exception ex )
                    {
                        LogWrapper.Logger.Error( "Parse TDAuto_RtData RtData Content error:" );
                        LogWrapper.Logger.Error( ex );
                    }
                }
                else
                {
                    devNum = i - 1;
                    break;
                }
            }

            return true;
        }

        public override bool ParseHead( string head )
        {
            bool result = false;
            string[ ] hs = head.Split( ',' );
            if ( hs.Length > 3 )
            {
                timeData = DateTime.Parse( hs[ 1 ] );
                devNum = Convert.ToInt16( hs[ 2 ] );
                modify = hs[ 3 ].Trim( );
                return true;
            }
            return result;
        }

        public override RtDataItem ParseBody( string body )
        {
            Console.WriteLine( body );
            string[ ] bs = body.Split( ',' );
            RtDataItem item = new RtDataItem( );
            item.SensorNO = GetSensorNO( bs );

            item.Value = bs[ ( int )TDAuto_RtDataFields.数值 ].Trim( );

            short state = Convert.ToInt16( bs[ ( int )TDAuto_RtDataFields.状态 ] );

            if ( devFile.dic_DevItem.ContainsKey( item.SensorNO ) )
            {
                DevItem devItem = devFile.dic_DevItem[ item.SensorNO ];

                // 采用正则表达式,进行数据提取处理
                item.Value = System.Text.RegularExpressions.Regex.Match( item.Value , @"^[ -]?\d*[.]?\d*" ).ToString( );

                // KJ126N
                // 2301,故障,8  0501,故障,16
                float value = 0.0F;// KJXX_Files.GetFloatFromString(item.Value);
                if ( !float.TryParse( item.Value , out value ) )
                {
                    item.Value = "0.00";
                }
                item = KJXXN_SetState( item , state , devItem );

                if ( devItem.SersorType == "模拟量" || devItem.SersorType.ToString( ) == "累计量" || devItem.SersorType.ToString( ) == "计数量" )
                {
                }
                else
                {
                    if ( item.State == "中断" )
                    {
                        value = ( short )TDAuto_DigitalStates.中断;
                    }

                    // 开关量状态转换
                    KJXXN_SetDigitalState( ref item , value , ref devItem );
                }

                if ( timeData.Year >= 2010 )
                {
                    item.Time = this.timeData;
                }
                Add( item );
            }
            else
            {
                LogWrapper.Logger.Error( item.SensorNO + " 无测点定义" );
            }
            return item;
        }

        private static string GetSensorNO( string[ ] bs )
        {
            return bs[ ( int )TDAuto_RtDataFields.分站号 ] + "-" + bs[ ( int )TDAuto_RtDataFields.测点号 ];
        }

        public static RtDataItem KJXXN_SetState( RtDataItem item , short n , DevItem devItem )
        {
            // 正常
            if ( n == 0 )
            {
                item.State = "正常";
                return item;
            }
            else if ( ( n & ( short )TDAuto_States.分站故障 ) == ( short )TDAuto_States.分站故障 )
            {
                item.State = "分站故障";
                return item;
            }

            else if ( ( n & ( short )TDAuto_States.调校 ) == ( short )TDAuto_States.调校 )
            {
                item.State = "调校";
                return item;
            }
            else if ( ( n & ( short )TDAuto_States.不巡检 ) == ( short )TDAuto_States.不巡检 )
            {
                item.State = "不巡检";
                return item;
            }
            else if ( ( n & ( short )TDAuto_States.暂停 ) == ( short )TDAuto_States.暂停 )
            {
                item.State = "暂停";
                return item;
            }
            else if ( ( n & ( short )TDAuto_States.超量程 ) == ( short )TDAuto_States.超量程 )
            {
                item.State = "超量程";
                return item;
            }
            else if ( ( n & ( short )TDAuto_States.故障 ) == ( short )TDAuto_States.故障 )
            {
                item.State = "故障";
                return item;
            }
            else if ( n > 265 )
            {
                item.State = "中断";
                return item;
            }
            else
            {
                item.State = "正常";
                return item;
            }
        }

        /// <summary>
        /// 开关量状态转换
        /// </summary>
        /// <param name="item"></param>
        /// <param name="value"></param>
        /// <param name="devItem"></param>
        public override void KJXXN_SetDigitalState( ref RtDataItem item , float value , ref DevItem devItem )
        {
            var state = ( TDAuto_DigitalStates )( short )value;
            if ( state >= TDAuto_DigitalStates.中断 )
            {
                state = TDAuto_DigitalStates.中断;
            }
            else
            {
                if ( ( int )value == ( int )TDAuto_DigitalStates.正常 )
                {
                    item.State = "正常";
                }
                else
                {
                    item.State = "异常";
                }
            }
            item.Value = item.State;
        }
    }

    /// <summary>
    /// 1,891,总回风尾端甲烷,4,1,%,,4.00,0.00,0.69,0.00,0,0
    /// 1,1154,四采区集中回风一氧化碳,1,1,PPm,,500.00,0.00,23.75,0.00,0,0
    /// 4,367,35KV1号电厂4403开关,28,2,分闸,合闸,0,0,0,0,0,0
    /// </summary>
    public enum TDAuto_Fields
    {
        分站号 = 0 ,
        测点号 = 1 ,
        安装位置 = 2 ,
        传感器名称 = 3 ,
        传感器类型 = 4 ,
        单位 = 5 ,
        量程下限 = 6 ,
        量程上限 = 7 ,
        报警下限 = 8 ,
        报警高限 = 9 ,
        断电值 = 10 ,
        复电值 = 11 ,
    }

    /// <summary>
    /// 5,145,0,0
    /// 5,146,0,256
    /// </summary>
    public enum TDAuto_RtDataFields
    {
        分站号 = 0 ,
        测点号 = 1 ,
        数值 = 2 ,
        状态 = 3 ,
    }

    public enum TDAuto_Types
    {
        未知 = 0 ,
        一氧化碳 = 1 ,
        风速 = 2 ,
        温度 = 3 ,
        瓦斯 = 4 ,
        压力/*风压*/ = 5 ,
        负压 = 6 ,
        水位 = 7 ,
        速度 = 8 ,
        煤位 = 9 ,
        流量 = 10 ,
        高低浓 = 11 ,
        有功功率 = 12 ,
        无功功率 = 13 ,
        电流 = 14 ,
        功率因数 = 15 ,
        频率 = 16 ,
        电压 = 17 ,
        有功电量 = 18 ,
        无功电量 = 19 ,
        钩数 = 20 ,
        产量 = 21 ,
        开停 = 22 ,
        开关 = 23 ,
        煤仓空满 = 24 ,
        风门 = 25 ,
        风机 = 26 ,
        风筒 = 27 ,
        状态 = 28 ,
        刀闸 = 29 ,
        过卷 = 30 ,
        位置 = 31 ,
        故障 = 32 ,
        烟雾 = 33 ,
        堵煤 = 34 ,
        一级失速 = 35 ,
        二级失速 = 36 ,
        一级跑偏 = 37 ,
        二级跑偏 = 38 ,
        拉绳 = 39 ,
        人数 = 40 ,
        H2S = 41 ,
        湿度 = 42 ,
        顶板压力 = 43 ,
        矿尘 = 44 ,
        位移 = 45 ,
        断电器 = 46 ,
        馈电器 = 47 ,
        氧气 = 48 ,
        其它1 = 49 ,
        其它2 = 50 ,
        浓度 = 51 ,
        其它 = 52
    } ;

    /// <summary>
    /// 正常（0）,  调校（4）  超量程（8）  分站故障（16）  不巡检（32）  暂停（64）  传感器故障（128) 故障（256 )
    ///
    /// 1,1410,0,0
    /// 1,1426,1,0
    /// 5,65,0,256
    /// </summary>
    public enum TDAuto_States
    {
        正常 = 0 ,
        调校 = 4 ,
        超量程 = 8 ,
        分站故障 = 16 ,
        不巡检 = 32 ,
        暂停 = 64 ,
        传感器故障 = 128 ,
        故障 = 256 ,
    }

    /*
     * 1<模拟量>、2<开关量>、3<控制量>、
        4<调节量>、5<计数量>、6<累计量>
    传感器类型的代码
    代码	传感器类型
    1	模拟量
    2	开关量
    3	调节量（模拟量输出）
    4	控制量（开关量输出）
    5	累计量
    6	计数量
    255	其它

     */

    public enum TDAuto_SensorTypes
    {
        模拟量 = 1 ,
        开关量 = 2 ,
        控制量 = 4 ,
        调节量 = 3 ,
        计数量 = 6 ,
        累计量 = 5 ,
        其它 = 255
    }

    /// <summary>
    /// 开关量测点状态
    ///
    /// 0 正常， 1 异常
    /// </summary>
    public enum TDAuto_DigitalStates
    {
        正常 = 0 ,
        异常 = 1 ,
        停 = 0 ,
        开 = 1 ,
        中断 = 2
    }
}